package com.chinatechstar;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

import com.chinatechstar.admin.mapper.SysRoleMapper;
import com.chinatechstar.admin.mapper.SysUrlMapper;
import com.chinatechstar.cache.redis.constants.ApplicationConstants;
import com.chinatechstar.cache.redis.util.RedisUtils;
import com.chinatechstar.gateway.filter.GatewayFilter;

/**
 * MSCode的入口网关启动类
 */
@SpringBootApplication(scanBasePackages = "com.chinatechstar")
@EnableResourceServer
@EnableOAuth2Client
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableDiscoveryClient
@EnableZuulProxy
@EnableScheduling
public class MSCodeGatewayApplication implements CommandLineRunner {

    @Autowired
    private SysUrlMapper sysUrlMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private RedisUtils redisUtils;

    public static void main(String[] args) {
        SpringApplication.run(MSCodeGatewayApplication.class);
    }

    @Bean
    public GatewayFilter gatewayFilter() {
        return new GatewayFilter();
    }

    /**
     * 初始化角色编码对应的URL授权数据到Redis缓存，供网关验证权限
     */
    @Override
    public void run(String... args) {
        List<String> roleCodeList = sysRoleMapper.queryRoleCodeList();
        for (String roleCode : roleCodeList) {
            List<String> url = sysUrlMapper.queryRoleUrl(roleCode);
            redisUtils.psetex(ApplicationConstants.URL_ROLECODE_PREFIX + roleCode, url == null ? Collections.emptyList().toString() : url.toString());
        }
    }

}
